<template>
  <div class="container">
    <div>
      <el-form inline>
        <el-form-item label="状态">
          <el-select v-model="query.status">
            <el-option label="未上传" value="0"></el-option>
            <el-option label="已上传" value="1"></el-option>
            <el-option label="全部" value=""></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button @click="upload = true">
            上传
          </el-button>
          <el-button @click="handleSelectionParse">
            解析已选择
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
        v-loading="imageLoading"
        :data="tableData"
        border
        max-height="600px"
        style="width: 100%;"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          prop="index"
          label="序号"
          width="100"
      >
        <template slot-scope="d">
          <span>{{+d.$index + 1 + ((page.current - 1) * page.size) }}</span>
        </template>
      </el-table-column>
      <el-table-column
          prop="index"
          label="图片"
      >
        <template slot-scope="{row}">
          <div>
            <el-image
                scroll-container=".el-table__body-wrapper"

                lazy v-for="item in row.images" style="width: 100px;height: 100px" :key="item" :src="item" :preview-src-list="row.images"></el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column
       label="是否上传"
       prop="uploadStatus"
      >
        <template slot-scope="{row}">
          <span>{{row.imageStatus == 0 ? '未上传': '已上传'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template slot-scope="scope">
          <el-button-group>
            <el-button
                @click="copyToTemplate(scope.row)">作为模板</el-button>
            <el-button
                type="success"
                @click="handleUploadParse([scope.row])">
              {{scope.row.imageStatus == 0 ? '上传' : '再次上传'}}
            </el-button>
            <el-button
                type="danger"
                icon="el-icon-delete"
                @click="handleDeleteImages([scope.row])">删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>

    </el-table>
      <div class="pager">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page.current"
            :page-sizes="[1000, 20, 30, 40]"
            :page-size="page.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total">
        </el-pagination>
      </div>
    <el-dialog title="上传" :visible.sync="upload">
      <el-form>
        <el-form-item label="面数">
          <el-select v-model="form.page">
            <el-option :value="1" label="1面"></el-option>
            <el-option :value="2" label="2面"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-upload
              class="upload-demo"
              ref="upload"
              :file-list="fileList"
              action="#"
              :multiple="false"
              :on-change="handleFileChange"
              limit="1"
              :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
            <div slot="tip" class="el-upload__tip">只能上传zip文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "uploadPhotos",
  data() {
    const errors = []
    for (let i = 0; i < 10; i++) {
      errors.push({
        src: "https://picsum.photos/300/200",
        examCode: "123456",
        source: "https://picsum.photos/300/200",
        sourceImg: "https://picsum.photos/1028/720",
      })
    }
    return {
      imageLoading: false,
      selectList:[],
      errors: errors,
      preview: false,
      fileList: [],
      previewSrc: '',
      upload: false,
      tableData: [],
      page: {
        current: 1,
        size: 1000,
        total: 0
      },
      parseData: null,
      query: {
        status: '0'
      },
      form: {
        page: 1
      },
      workId: ""
    }
  },
  created() {
    this.workId = this.$route.query.workId
  },
  async mounted() {

    if (!this.workId) {
      return
    }
    await this.handleQueryImages();
  },
  watch: {
    "query": {
      handler: function () {
        this.handleQueryImages()
      },
      deep: true
    }
  },
  methods: {
    async handleDeleteImages(rows) {
      let res = await this.$HttpPost.paperEditor.deleteImages.request(rows.map(item => {
        return {
          id: item.id
        }
      }))
      if (res.code !== 200) {
        this.$message.warning(res.message)
        return
      }
      this.handleQueryImages()
    },
    async handleSelectionParse() {
      if (this.selectList == null || this.selectList.length <= 0) {
        this.$message.warning("请选择")
        return
      }
      const selectList = this.selectList
      try {
        this.imageLoading = true
        const res = await this.handleUploadParse(selectList)
      } finally {
        this.imageLoading = false
      }
    },
    copyToTemplate(row) {
      window.localStorage.setItem("templateImgs", JSON.stringify(row.images))
      this.$router.push({
        path: "/paper-parse-template/list",
        query: {
          workId: this.$route.query.workId
        }
      })
    },
    async handleUploadParse(rowList) {
      if (this.parseData == null) {
        await this.queryOkParseList()
      }
      if (this.parseData == null) {
        this.$message.warning("没有解析模板")
        return
      }
      const res = await this.$api.uploadHttpUrls({
        templateId: this.parseData.id,
        workId: this.workId,
        items: rowList.map(item => {
          return {
            urls: item.images,
            imageId: item.id
          }
        }),
        config: this.parseData
      })
      if (res.code === 200) {

        this.handleQueryImages()
      }
    },

    handleSelectionChange(selectList) {

      this.selectList = selectList
    },
    async queryOkParseList() {

      let $loading = this.$fastLoading();

      try {
        let res = await this.$api.parseOkList({
          workId: this.workId
        })
        if (res.code !== 200) {
          return;
        }
        if (res.data.length <= 0) {
          return;
        }
        this.parseData = res.data[0];
      } finally {
        $loading.close()
      }
    },
    handleConsole(d) {
    },
    async submitUpload() {

      let res = await this.$api.uploadZip(this.fileList[0].raw,
          {
            page: this.form.page,
            workId: this.workId
          },
          window.origin + "/smart-question-api/bs-work-editor-upload/v2/add_images"
      )
      if (res.code !== 200) {
        this.$message.warning("上传失败")
        return
      }
      this.handleQueryImages()
      this.$message.success("上传成功")
      this.upload = false
    },
    handleFileChange(file, fileList) {
      if (fileList.size > 1) {
        this.fileList = [file]
      } else {
        this.fileList = fileList
      }
    },
    handleSizeChange(size) {
      this.page.size = size
      this.handleQueryImages()
    },
    handleCurrentChange(current) {
      this.page.current = current
    },
    async handleQueryImages() {
      let params = {
        current: this.page.current,
        size: this.page.size,
        data: {
          workId: this.workId,
          imageStatus: this.query.status,
        }
      };
      let res = await this.$api.uploadImagePage(
          params
      )
      if (res.code !== 200) {
        this.$message.warning(res.message)
        return
      }
      this.tableData = res.data.data
      this.page.total = res.data.total

    },
  }
}
</script>

<style scoped type="less">
.container {
  box-sizing: border-box;
  height: 100%;
  width: 100%;
  overflow: auto;

  //justify-content: space-around;

  .container_body {
    display: flex;
    flex-wrap: wrap;

    .error_code_container {
      padding: 1px;
      width: 300px;

      .error_code_img {
        height: 200px;

      }

      .error_code_info {
        margin-top: 10px;

      }

      .error_code_controller {

      }
    }
  }

  .container_controller {
    display: flex;
    .left_margin {
      flex: 1;
    }
    .buttons {
      margin-right: 30px;

    }
  }

}
</style>
